package com.wm.web.servlet;

import javax.servlet.http.*;
//import org.apache.commons.lang.math.NumberUtils;

import org.apache.commons.lang.*;
import org.apache.commons.logging.*;

import com.wm.comm.Constant;

public class UserCookie {
	private static final Log logger = LogFactory.getLog(UserCookie.class);
	private HttpServletRequest request;
	private HttpServletResponse response;
	private String defaultDomain = "";
	
	public UserCookie(HttpServletRequest request, HttpServletResponse response) {
	    this.request = request;
	    this.response = response;
	  }
	public String getCookie(String name) {
	    Cookie cookies[] = request.getCookies();
	    Cookie sCookie = null;
	    try {
	        if (cookies != null && cookies.length > 0) {
	        	for (int i = 0; i < cookies.length; i++) {
	                sCookie = cookies[i];
	                if (sCookie.getName().equals(name)) {
	                	return sCookie.getValue();
	                }
	        	}
	        }
	    }catch (Exception ex) {
	    	logger.error(ex);
	    }
	    return "";
	}
	
	public void addCookie(String name, String value, int maxage) {
	    Cookie cookies = new Cookie(name, value);
	    cookies.setPath("/");
	    cookies.setMaxAge(maxage);
	    //cookies.setMaxAge(30 * 60);
	    if (!defaultDomain.equalsIgnoreCase("")) {
	      cookies.setDomain(defaultDomain);
	    }
	    this.response.addCookie(cookies);
	}
	
	public void addCookie(String name, String value) {
	    Cookie cookies = new Cookie(name, value);
	    cookies.setPath("/");
	    if (!defaultDomain.equalsIgnoreCase("")) {
	      cookies.setDomain(defaultDomain);
	    }
	    this.response.addCookie(cookies);
	}
	
	public void removeCookie(String name) {
		addCookie(name, "",0);
	}
	
	
	public void removeAllCookies() {
		addCookie(Constant.USER_COOKIE_KEY, "",0);
	}
}
